//封装axios
import axios from 'axios'
import {getTokenValue, isToken} from './tokenUtil';
//请求拦截
axios.interceptors.request.use((config) => {
// 是否需要设置 token
  const isToken = (config.headers || {}).isToken === false
  if (getTokenValue() && !isToken) {
    config.headers.Authorization = 'Bearer ' + getTokenValue()
  }
  return config
})

export interface dataType{
  code:number
  data:any,
  msg:string
}
//响应拦截
axios.interceptors.response.use(
  (res) => {
    const data = res.data;
    const status = data.code
    const msg = data.msg
    checkStatus(status,msg)
    return data
  },
  (error) => {
    //失败，处理http网络错误
    const msg = error.response.message
    const status = error.response.status
    checkStatus(status,msg);
    return Promise.reject(error)
  }
)

const checkStatus = (status:number,msg:string) => {
  switch (status) {
    case 200:
      return
    case 401:
      if (isToken()) {
        msg = '登录信息过期，请重新登录！！';
      } else {
        msg = '请先登录！！';
      }
      // store.dispatch(toLogOut())
      break
    case 403:
      msg = '无权限访问'
      break
    case 404:
      msg = '请求接口地址错误'
      break
    case 500:
      msg = '服务器出现问题'
      break
    default:
      msg = '网络出现问题'
      break
  }
}

//对外暴露
export default axios

